appPath = location.origin + ""
window.TS =
	appPath: appPath
	api: {}
	app: {}

api = {}
window.TS.api = api
window._w = window["when"]

AjaxOption = (type, data, settings)->
	this.type = type;

	if type == "POST" || type == "PUT"
		this.data = data && JSON.stringify(data);
		this.contentType = "application/json";
	else
		this.data = data;

failHandler = (jqxhr)->
	alert jqxhr.message;

api.get = (relativeUrl, data)->
	$.ajax(appPath + relativeUrl, new AjaxOption("GET", data)).fail(failHandler);

api.getView = (relativeUrl, data)->
	$.get(appPath + relativeUrl, data)

api.post = (relativeUrl, data)->
	$.ajax(appPath + relativeUrl, new AjaxOption("POST", data)).fail(failHandler);

api.delete = (relativeUrl)->
	$.ajax(appPath + relativeUrl, new AjaxOption("DELETE", null)).fail(failHandler);

#TODO format
api.formatDate = (date)->
	date ?= new Date()
	year = date.getFullYear()
	month = date.getMonth() + 1
	month = if month.toString().length >= 2 then month else "0" + month
	day = date.getDate().toString()
	day = if day.length >= 2 then day else "0" + day
	hour = date.getHours().toString()
	hour = if hour.length >= 2 then hour else "0" + hour
	min = date.getMinutes().toString()
	min = if min.length >= 2 then min else "0" + min
	second = date.getSeconds().toString()
	second = if second.length >= 2 then second else "0" + second
	return "#{year}-#{month}-#{day} #{hour}:#{min}:#{second}"


$.fn.extend
	serializeObject: ->
		data = this.serializeArray();
		o = {}
		$.each data, ()->
			o[this.name] = this.value
		return o

api.promiseView = (name) ->
	rq = $.get(name + ".html", "html", 'html')
	return _w(rq).then (viewHtml) ->
		$view = $(viewHtml)
		$('.main-content').html $view
		return $view
